#!/usr/bin/python
# -*- coding: utf8 -*-
"""Commande definition : obtenir la définition d'un mot via google"""
from BeautifulSoup import BeautifulSoup
from getpage import getpage
from time import sleep
import re

import xmpp
from plugin import Plugin

class DefineModule(Plugin):
    infos = {'name': 'Definition',
            'author': 'magnetik',
            'version': '0.1',
            'website':'http://blog.magnetik.org',
            'handlers': ['define','definition'],
            'cmd': 'define',
            }
    doc=_(u"Commande retourtant la ou les définitions d'un mot ou expression")
    
    def define(self,conn,user,command,args,mess,lang):
        if (len(args) == 0):
            conn.send(xmpp.protocol.Message(mess.getFrom(),_(u"Entrez un mot !"),"chat"))
        define=getdefineofgoogle(args, lang)
        if define:
            if (type(define) == type([])):
                define.insert(0,_(u"Definition(s) de %s :")%args)
            for message in define:
                conn.send(xmpp.protocol.Message(mess.getFrom(),message,"chat"))
                sleep(0.5)
        else: return conn.send(xmpp.protocol.Message(mess.getFrom(),_(u"Aucune définition"),"chat"))

def getdefineofgoogle(text, lang):
    lang=unicode(lang)
    #On récupère la page
    try:
        get=getpage("http://www.google.com/search?",{'q': 'define:' + text, 'oi': 'define', 'defl' : lang})
        page=get.get()
    except:
        return _(u"Impossible de se connecter. Réessayer plus tard")
    #Parsage HTML
    soup = BeautifulSoup(page)
    define=[]
    # On cherche les li pour afficher le contenu 
    for incident in soup('li'):
        what=incident.contents[0]
        #print dir(incident.contents[2])
        #On ajoute la définition a la liste
        define.append(re.sub("&#([0-9]+);", lambda regs: unichr(int(regs.group(1))), what.strip()) + "\r\n> http://" + incident.contents[2].find("font").string)
    if (len(define) > 0):
        return define
    else:
        return
    

